import { useState, useEffect, useRef } from 'react';

import useWindowWidth from '@/hooks/event/use-window-width';
import { useOrchestrationStore } from '@/store/orchestrationStore';

import { SvgIcon } from '@/components/icon';

import './header.css';
import Back from '@/components/router/Back';
import { useUserState } from '@/store/userStore';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { useParams, useRouter } from '@/router/hooks';

import { UserDropdownMenu } from '@/components/menus';

interface HeaderProps {
  onHistoryClick?: () => void;
  onHomeClick?: () => void;
  onDashboardClick?: () => void;
  onFusionAppClick?: () => void;
  workflowDebug?: boolean;
  currentView?: string;
  showAgentHistory?: boolean;
}

const AppHeader: React.FC<HeaderProps> = ({
  onHistoryClick,
  onHomeClick,
  onDashboardClick,
  onFusionAppClick,
  workflowDebug = false,
  currentView,
  showAgentHistory,
}) => {
  const [logoShow, setLogoShow] = useState(false);
  const router = useRouter();

  const { isPc } = useWindowWidth();
  const { configurations, workflow, setAppDetail, special_app_lable } = useOrchestrationStore();
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerWidth, setContainerWidth] = useState(0);

  // useEffect(() => {
  //   console.log('configurations', configurations)
  // }, [configurations])
  // const { appDetail } = useContextSelector(AppContext, (v) => v);

  // console.log(77777777777777, configurations);

  const { appName, appLogo } = useOrchestrationStore();

  const isConfigAvailable = configurations.length != 0;
  const appNameConfig =
    (configurations.find((config) => config.name === 'app_name')?.default_value as string) ||
    appName;
  const appLogoConfig =
    (configurations.find((config) => config.name === 'app_logo')?.default_value as string) ||
    appLogo;
  const isInChatPage = location.pathname.includes('/apps/chat');
  const isInFusionPage = location.pathname.includes('/fusion');

  const { isPublic } = useParams() as { isPublic: string };
  const isPublicFlag = isPublic == 'true';

  const [isSafariSupported, setIsSafariSupported] = useState(true);

  useEffect(() => {
    const userAgent = navigator.userAgent;
    const isSafari = /^((?!chrome|android).)*safari/i.test(userAgent);

    if (isSafari) {
      const safariVersionMatch = userAgent.match(/version\/(\d+(:?\.\d+)*)/i);
      if (safariVersionMatch && safariVersionMatch[1]) {
        const safariVersion = parseFloat(safariVersionMatch[1]);
        // 如果 Safari 版本低于 15.4，设置不支持
        if (safariVersion < 15.4) {
          setIsSafariSupported(false);
        }
      }
    }
  }, []);

  useEffect(() => {
    if (containerRef.current) {
      const updateWidth = () => {
        setContainerWidth(containerRef.current?.offsetWidth || 0);
      };

      updateWidth();

      const resizeObserver = new ResizeObserver(updateWidth);
      resizeObserver.observe(containerRef.current);

      return () => {
        // setAppDetail({});
        if (containerRef.current) {
          resizeObserver.unobserve(containerRef.current);
        }
      };
    }
  }, []);

  const { isGuest, isAdmin } = useUserState();
  const { isInOrchestrationPage } = useOrchestrationStore();

  return (
    <>
      <div
        className={
          isPc
            ? 'flex items-center justify-center'
            : 'mx-2 my-1 flex h-[48px] items-center justify-center rounded-[12px] z-[100]'
        }
        style={{ position: 'relative' }}
        ref={containerRef}
      >
        <div
          className={`flex justify-between ${isPc ? 'h-[60px] px-6' : 'px-2'} py-2`}
          style={{
            width: '100%',
            position: 'relative',
            zIndex: 2,
          }}
        >
          {!isPc && (
            <div className="relative flex h-full items-center">
              {isGuest || !isPublicFlag ? (
                <UserDropdownMenu />
              ) : (
                <div
                  onClick={() => {
                    router.push('/worklayouts/');
                  }}
                  className="flex cursor-pointer items-center justify-center p-1"
                >
                  <SvgIcon icon="ai-chat-back" size={24} />
                </div>
              )}
            </div>
          )}
          {isPc && (
            <div className="flex items-center">
              {!isInOrchestrationPage && (
              <div
                className="jr-step-3 flex items-center justify-center"
                style={{
                  borderRadius: '8px',
                  display: 'flex',
                  padding: 'unset',
                }}
              >
                <div
                  style={{ paddingRight: '10px', display: 'flex' }}
                  onClick={() => !isPc && setLogoShow(!logoShow)}
                >
                  {(isConfigAvailable || workflow) && (
                    <AvatarDisplay src={appLogoConfig} size={35} className="h-[35px] w-[35px]" />
                  )}
                </div>

                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <div
                    // font-[Alimama ShuHeiTi]
                    className={`
                      overflow-hidden
                      text-ellipsis
                      whitespace-nowrap
                      text-[20px]
                      font-bold
                      text-[#1D2129]
                    `}
                    style={{
                      fontFamily: 'sans-serif',
                      maxWidth:
                        isPc || isInOrchestrationPage
                          ? 'unset'
                          : isGuest
                          ? 'calc(100vw - 150px)'
                          : isAdmin
                          ? 'calc(100vw - 220px)'
                          : 'calc(100vw - 200px)',
                    }}
                  >
                    {(isConfigAvailable || workflow) && appNameConfig}
                  </div>
                </div>

                {/* {isPc && currentView == 'homepage' && (
                  <div className="pl-5 text-center text-[14px] font-normal leading-[22px] text-[#4E5969]">
                  新对话
                  </div>
                  )} */}
                {/* )} */}
              </div>
              )}
              {/* 预览与调试文字 */}
              {isInOrchestrationPage && (
                <div
                  className="mr-4 text-text-5 text-[16px] font-semibold gap-2 flex items-center justify-center"
                >
                  <SvgIcon icon={`ai-orch-play`} size={20} />
                  预览与调试
                </div>
              )}
            </div>
          )}
          <div className={`flex ${isPc ? 'gap-4' : 'gap-2'} items-center justify-center`}>
            {currentView != 'homepage' && (
              <div onClick={onHomeClick} className="cursor-pointer p-1">
                {/* <SvgIcon icon={`ri-homepage-new`} size={25} /> */}
                <SvgIcon icon={`ai-chat-new`} size={24} />
              </div>
            )}

            {!workflowDebug && !isInOrchestrationPage && (
              <div
                onClick={onHistoryClick}
                className={`cursor-pointer p-1 ${
                  currentView == 'history' || showAgentHistory
                    ? 'rounded-[6px] bg-@brand-color-home'
                    : ''
                }`}
              >
                {/* <SvgIcon icon={`ri-homepage-history`} size={25} /> */}
                <SvgIcon icon={`ai-chat-history`} size={24} />
              </div>
            )}

            {location?.pathname?.includes('fusion') && !isPc && (
              <div
                onClick={onFusionAppClick}
                className={`cursor-pointer p-1 ${
                  currentView == 'fusion-app' ? 'rounded-[6px] bg-@brand-color-home' : ''
                }`}
              >
                <SvgIcon icon={`ai-chat-fusion`} size={24} />
              </div>
            )}

            {!isPc && isAdmin && (
              <div
                onClick={onDashboardClick}
                className={`cursor-pointer p-1 ${
                  currentView == 'dashboard' ? 'rounded-[6px] bg-@brand-color-home' : ''
                }`}
              >
                {/* <SvgIcon icon={`ri-homepage-dashboard`} size={25} /> */}
                <SvgIcon icon={`ai-chat-dashboard`} size={24} />
              </div>
            )}
            {/* {!isPc && isAdmin && isInFusionPage && (
              <div onClick={onDashboardClick} className={`cursor-pointer p-1 ${currentView == 'public-agent' ? 'bg-input-gray rounded-[6px]' : ''}`}>
                <SvgIcon icon={`ai-chat-app-store`} size={24} />
              </div>
            )} */}
            {isPc && (isInChatPage || isInFusionPage) && <UserDropdownMenu />}
          </div>
        </div>
      </div>
    </>
  );
};

export default AppHeader;
